package com.qiangesoft.rabbitmq.producer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

/**
 * 消息路由失败回退配置
 *
 * @author qiangesoft
 * @date 2024-05-08
 */
@Slf4j
@Configuration
public class ReturnsCallbackConfig implements ApplicationContextAware {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
        // 消息路由失败退回，设置ReturnsCallback【消息到达交换机没有达到队列】
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returned) {
                log.info("触发【publisher return】机制");
                log.error("消息投递失败未到达队列，应答码：{}，原因：{}，交换机：{}，路由键：{}，消息：{}", returned.getReplyCode(), returned.getReplyText(),
                        returned.getExchange(), returned.getRoutingKey(), returned.getMessage());
            }
        });
    }

}